<?php

namespace app\admin\model;

use think\Db;
use think\Model;
use think\Session;

class auser extends Model
{
    public static function auserAdd($data)
    {
        $data['update_time'] = $data['create_time'] = time();
        $id = self::field('adname,password,salt,status,rid,create_time,update_time')->insertGetId($data);
        if (!$id) throw new \Exception('添加用户失败');

        return $id;
    }

    public static function auserUpdate($data)
    {
        $id = $data['adid'];
        $data['update_time'] = time();
        $result = self::field('adid,adname,password,salt,status,rid,create_time,update_time')->update($data);
        if (!$result) throw new \Exception('修改用户失败');
        return $id;
    }

    public static function auserDel($where)
    {
        $result = self::where($where)->delete();
        if (!$result) throw new \Exception('删除用户失败');
    }

    public static function encrypt($str, $salt)
    {
        return md5($str . $salt);
    }

    public static function salt($length = 4)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        return substr($randStr, 0, $length);
    }

    public static function checkPassword($password1, $salt, $password2)
    {
        return self::encrypt($password1, $salt) == $password2;
    }

    public static function login($user)
    {
        //获取角色信息
        $arole = Db::name('arole')->find($user['rid']);
        if (empty($arole)) throw new \Exception('获取不到用户角色信息');

        $session = [
            'adid' => $user['adid'],
            'adname' => $user['adname'],
            'status' => $user['status'],
            'rid' => $user['rid'],
            'rolename' => $arole['rolename'],
            'powerid' => $arole['powerid'],
        ];
        Session::set('user', $session, 'admin');
    }

    public static function logout()
    {
        Session::delete('user', 'admin');
    }
}